package com.totoro.controller.request;

import com.totoro.pojo.*;
import com.totoro.service.*;
import com.totoro.utils.TotoroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author TOTORO
 * @date 2021/6/27 11:41
 * 卖家中心页面跳转控制器
 */
@Controller
@RequestMapping("/seller")
public class SellerRequestController {
    private static final Integer CATEGORY_ATTR  = 2;
    private static final Integer CUSTOMIZE_ATTR  = 7;

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AttributeService attributeService;
    @Autowired
    private UserService userService;
    @Autowired
    private ColorRgbService rgbService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private SellerService sellerService;
    @Autowired
    private ProductService productService;
    @Autowired
    private EvaluationService evaluationService;
    @Autowired
    private ShopService shopService;
    @Autowired
    ReturnService returnService;
    @Autowired
    AdminService adminService;

    /**
     * 前往卖家中心-首页
     * @param session
     * @return
     */
    @RequestMapping("/sellerHome")
    public String goSellerHome(HttpSession session, Model model){
        // 检测是否登录
        User user = (User) session.getAttribute("user");
        if(null == user){
            return "redirect:/login.htm";
        }
        // 判断用户是否为卖家
        Seller seller = sellerService.findSellerIdByUserId(user.getUserId());
        boolean isSeller = false;
        if(seller != null) {
            isSeller = true;
            int awaitPay = 0;
            int awaitShip = 0;
            int awaitReturn = 0;
            int awaitEva = 0;
            int alreadyShip = 0;
            int successOrder = 0;
            int closedOrder = 0;
            // 获取待发货，待评价等等数量
            SellerOrderFind sellerOrderFind = new SellerOrderFind(seller.getId(), "1=1", 0, null, null, null, null, null, 999, 999, false, 0);
            List<MarketOrder> marketOrderList = orderService.superFindSellerOrderId(sellerOrderFind);
            for (MarketOrder marketOrder : marketOrderList) {
                if(marketOrder.getOrderStatus() ==1){
                    awaitPay++;
                }
                if(marketOrder.getOrderStatus() == 2){
                    awaitShip++;
                }
                if(marketOrder.getOrderStatus() == 6){
                    awaitReturn++;
                }
                if(marketOrder.getOrderStatus() == 4){
                    awaitEva++;
                }
                if(marketOrder.getOrderStatus() == 3){
                    alreadyShip++;
                }
                if(marketOrder.getOrderStatus() == 5){
                    successOrder++;
                }
                if(marketOrder.getOrderStatus() == 8){
                    closedOrder++;
                }
            }
            model.addAttribute("awaitPay", awaitPay);
            model.addAttribute("awaitShip", awaitShip);
            model.addAttribute("awaitReturn", awaitReturn);
            model.addAttribute("awaitEva", awaitEva);
            model.addAttribute("alreadyShip", alreadyShip);
            model.addAttribute("successOrder", successOrder);
            model.addAttribute("closedOrder", closedOrder);
        }
        model.addAttribute("isSeller", isSeller);
        return "include/seller/seller_index";
    }

    /**
     * 前往卖家中心发布商品-输入商品类别
     * @param session
     * @return
     */
    @RequestMapping("/productCategory")
    public String goProductCategory(HttpSession session){
        // 检测是否登录
        User user = (User) session.getAttribute("user");
        if(null == user){
            return "redirect:/login.htm";
        }
        User finalUser = userService.findUser(user.getUserId());
        // 检测是否为卖家
        boolean isSeller = finalUser.getIsSeller()==1?true:false;
        if(!isSeller){
            return "redirect:/";
        }

        return "include/seller/category";
    }


    /**
     * 前往商品发布 - 填写属性
     * @param cid
     * @param model
     * @return
     */
    @RequestMapping(value = "/productAttribute/{cid}/{isVirtual}", method = RequestMethod.GET)
    public String initAttr(@PathVariable int cid, @PathVariable boolean isVirtual, Model model, HttpSession session){

        int skuCid = cid;
        // 检测是否登录
        User user = (User) session.getAttribute("user");
        if(null == user){
            return "redirect:/login.htm";
        }
        // 检测是否为卖家
        boolean isSeller = user.getIsSeller()==1?true:false;
        if(!isSeller){
            return "redirect:/";
        }


        // 获取spu集合，存进rq传递值
        boolean isCt = false;
        List<SpuKey> list = attributeService.findSpu(cid);
        // 获取有多少必填项
        int mustFill = 0;
        for (SpuKey spuKey : list) {
            if(spuKey.getMustFill() == 1){
                mustFill++;
            }
        }
        // 保存
        model.addAttribute("mustFill", mustFill);

        //五次分类，循环五次查找父级属性
        for (int i = 0; i < 5; i++) {
            list = attributeService.findSpu(cid);
            if (list.size() > 0) {
                break;
            }

            cid = getParentCategoryId(cid);
            System.err.println(cid);
            // 如果是空
            if(cid == 99999){
                list = null;
                break;
            }
        }

        boolean isBy = false;
        // 获取该类别是否有类目属性，list不等于null才计算
        if(list!=null){
            for (SpuKey spuKey : list) {
                if(spuKey.getSpuListId() == CATEGORY_ATTR){
                    isCt = true;
                    break;
                }
            }
            // 获取该类别是否自定义
            isBy = categoryService.findIsBy(cid);
            // 如果该类别没有，试图获取它的父类别是否拥有
            if(!isBy){
                int parentId = getParentCategoryId(cid);
                isBy = categoryService.findIsBy(parentId);
            }
        }
        // 是否拥有自定义属性
        model.addAttribute("isBy", isBy);
        model.addAttribute("spus", list);
        model.addAttribute("isCt", isCt);
        model.addAttribute("cid", cid);
        model.addAttribute("isVirtual", isVirtual);


        // sku 列表
        List<SkuKey> skuLists = attributeService.findSkuListById(skuCid);
        //五次分类，循环五次查找父级属性
        for (int i = 0; i < 5; i++) {
            skuLists = attributeService.findSkuListById(skuCid);
            if (skuLists.size() > 0) {
                break;
            }

            int parentId = getParentCategoryId(skuCid);
            skuCid = parentId;
            // 如果是空
            if(skuCid == 99999){
                skuLists = null;
                break;
            }
        }
        model.addAttribute("skuList", skuLists);
        // 获取颜色
        List<ColorRgb> colorRgbs = rgbService.findAllColor();
        model.addAttribute("colors", colorRgbs);
        return "include/seller/attribute";
    }

    /**
     * 跳转至已卖出的宝贝
     * @return
     */
    @RequestMapping("/listSoldItems")
    public String goListSoldItems(@RequestParam(value = "tabCode", required = false, defaultValue = "latest3Months") String tabCode,
                                  @RequestParam(value = "auctionId", required = false, defaultValue = "0") int auctionId,
                                  @RequestParam(value = "itemName", required = false, defaultValue = "") String itemName,
                                  @RequestParam(value = "buyerNick", required = false, defaultValue = "") String buyerNick,
                                  @RequestParam(value = "bizOrderId", required = false, defaultValue = "") String bizOrderId,
                                  @RequestParam(value = "startTime", required = false, defaultValue = "") String startTime,
                                  @RequestParam(value = "endTime", required = false, defaultValue = "") String endTime,
                                  @RequestParam(value = "evaStatus", required = false, defaultValue = "999") int evaStatus,
                                  @RequestParam(value = "saleAfter", required = false, defaultValue = "999") int saleAfter,
                                  @RequestParam(value = "notShowCloseOrder", required = false, defaultValue = "false") boolean notShowCloseOrder,
                                  @RequestParam(value = "curr", required = false, defaultValue = "1") int curr,
                                  HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        // 判断是否为卖家
        User finalUser = userService.findUser(user.getUserId());
        boolean isSeller = finalUser.getIsSeller()==1?true:false;
        if(!isSeller){
            return "redirect:/";
        }
        String sql = "";
        // 计算基本所有条件 - 状态与时间区间
        switch (tabCode){
            case "latest3Months":
                sql = "t1.create_time > date_sub(curdate(), interval 3 month)";
                break;
            case "waitBuyerPay":
                sql = "t1.order_status = 1";
                break;
            case "waitSend":
                sql = "t1.order_status = 2";
                break;
            case "haveSendGoods":
                sql = "t1.order_status = 3";
                break;
            case "refunding":
                sql = "t1.order_status = 6";
                break;
            case "waitRate":
                sql = "t1.order_status = 4";
                break;
            case "success":
                sql = "t1.order_status = 5";
                break;
            case "closed":
                sql = "t1.order_status = 8";
                break;
            case "before3Months":
                sql = "t1.create_time < curdate() - interval 3 month";
                break;
        }

        // 获取卖家id
        Seller seller = sellerService.findSellerIdByUserId(user.getUserId());
        SellerOrderFind sellerOrderFind = new SellerOrderFind(seller.getId(), sql, auctionId, itemName, buyerNick, bizOrderId.trim(), startTime, endTime, evaStatus, saleAfter, notShowCloseOrder, curr);
        List<MarketOrder> marketOrderList = orderService.superFindSellerOrderId(sellerOrderFind);
        model.addAttribute("marketOrders", marketOrderList);
        // 计算这次总数量，不分页状态
        sellerOrderFind.setCurr(0);
        int allPage = orderService.superFindSellerOrderId(sellerOrderFind).size();
        model.addAttribute("allPage", allPage);

        // 根据详情订单号获取所有退货款订单号，map键值对
        Map<String, PrimaryReturn> map = new HashMap<>();
        for (MarketOrder marketOrder : marketOrderList) {
            for (MarketSrOrder marketSrOrder : marketOrder.getMarketSrOrderList()) {
                PrimaryReturn primaryReturn = returnService.findPrimaryReturnByMarketSrId(marketSrOrder.getId());
                if(primaryReturn!=null){
                    map.put(marketSrOrder.getId()+"", primaryReturn);
                }
            }
        }
        model.addAttribute("primaryReturnMap", map);
        return "include/seller/list_sold_items";
    }

    /**
     * iframe 的跳转关闭订单
     * @param bizOrderId
     * @return
     */
    @RequestMapping("/cancel_order")
    public String goCancelOrder(@RequestParam("bizOrderId") String bizOrderId){
        return "include/seller/contain/cancel_order";
    }


    /**
     * 前往买家评论中心
     * @return
     */
    @RequestMapping("/evaluationCenter")
    public String goEvaluateCenter(Model model){
        SuperEvaluationFind superEvaluationFind = new SuperEvaluationFind();
        superEvaluationFind.setSlid(1);
        List<ProductComment> productComments = evaluationService.findUserAllEvaluationBySlid(superEvaluationFind);
        // 统计大概数据
        // 1、计算待解释的评论数量
        int stayReply = 0;
        // 2、好评
        // 2-1、最近一周好评
        int thisWeekGood = 0;
        // 2-2、最近一月好评
        int thisMonthOneGood = 0;
        // 2-3、最近六月好评
        int thisMonthSixGood = 0;
        // 3、中评
        // 3-1、最近一周中评...
        int thisWeekMedium = 0;
        int thisMonthOneMedium = 0;
        int thisMonthSixMedium = 0;
        // 4、差评
        int thisWeekBad = 0;
        int thisMonthOneBad = 0;
        int thisMonthSixBad = 0;

        // 信用总计
        int thisWeekCount = 0;
        int thisMonthOneCount = 0;
        int thisMonthSixCount = 0;
        // 累计评价
        int allEvaluation = productComments.size();

        for (ProductComment productComment : productComments) {
            // 1
            if(productComment.getMarketSrOrder().getSellerIsReply() == 0){
                stayReply++;
            }
            // 2 3 4
                if(TotoroUtils.isThisWeek(productComment.getCreateTime())){
                    if (productComment.getCommentScore() == 1) {
                        thisWeekGood++;
                    } else {
                        if (productComment.getCommentScore() == 0) {
                            thisWeekMedium++;
                        } else {
                            thisWeekBad++;
                        }
                    }
                    thisWeekCount+=productComment.getCommentScore();
                }
                if(TotoroUtils.isThisYearMonth(productComment.getCreateTime(), 1)){
                    if (productComment.getCommentScore() == 1) {
                        thisMonthOneGood++;
                    } else {
                        if (productComment.getCommentScore() == 0) {
                            thisMonthOneMedium++;
                        } else {
                            thisMonthOneBad++;
                        }
                    }
                    thisMonthOneCount+=productComment.getCommentScore();
                }
                if(TotoroUtils.isThisYearMonth(productComment.getCreateTime(), 6)){
                    if (productComment.getCommentScore() == 1) {
                        thisMonthSixGood++;
                    } else {
                        if (productComment.getCommentScore() == 0) {
                            thisMonthSixMedium++;
                        } else {
                            thisMonthSixBad++;
                        }
                    }
                    thisMonthSixCount+=productComment.getCommentScore();
                }
        }
        // 获取该卖家，用来拿信用分
        Seller seller = sellerService.findSellerBySlid(1);
        // 获取信用分属性
        CreditLevel creditLevel = sellerService.findCreditLevelByCreditScore(seller.getCredibilityScore());
        // 获取与下一级相差多少信用分 （如果满级则不查询）
        int differCreditScore = 0;
        if (creditLevel.getCreditLevelId() < CreditLevel.MAX_LEVEL){
            creditLevel.setNowScore(seller.getCredibilityScore());
            differCreditScore = sellerService.findNextLevelDifferCreditScore(creditLevel);
        }
        model.addAttribute("creditLevel", creditLevel);
        model.addAttribute("differCreditScore", differCreditScore);

        // 获取店铺
        Shop shop = shopService.findShopBySlid(1);
        // 计算卖家分，宝贝分，物流分 （总分除评价数）
        double sellerStar = Double.parseDouble(String.format("%.2f", (double)shop.getShopSellerStar() / allEvaluation));
        double babyStar = Double.parseDouble(String.format("%.2f", (double)shop.getShopBabyStar() / allEvaluation));
        double logisticsStar = Double.parseDouble(String.format("%.2f", (double)shop.getShopLogisticsStar() / allEvaluation));
        model.addAttribute("sellerStar", sellerStar);
        model.addAttribute("babyStar", babyStar);
        model.addAttribute("logisticsStar", logisticsStar);
        // 获得同行最高分
        Shop otherMaxShop = shopService.findOtherMaxScore(1);
        // 计算自己与同行的平均分差距
        // 获得同行最高的评论数
        int otherMaxProductComments = evaluationService.findUserAllEvaluationBySlid(new SuperEvaluationFind(otherMaxShop.getSlid())).size();
        double otherMaxSellerStar =  Double.parseDouble(String.format("%.2f", (double)otherMaxShop.getShopSellerStar() / otherMaxProductComments));
        double otherMaxBabyStar = Double.parseDouble(String.format("%.2f", (double)otherMaxShop.getShopBabyStar() / otherMaxProductComments));
        double otherMaxLogisticsStar = Double.parseDouble(String.format("%.2f", (double)otherMaxShop.getShopLogisticsStar() / otherMaxProductComments));
        model.addAttribute("gapSellerStar", Double.parseDouble(String.format("%.2f", (double)sellerStar - otherMaxSellerStar)));
        model.addAttribute("gapBabyStar", Double.parseDouble(String.format("%.2f", (double)babyStar - otherMaxBabyStar)));
        model.addAttribute("gapLogisticsStar", Double.parseDouble(String.format("%.2f", (double)logisticsStar - otherMaxLogisticsStar)));
        System.out.println(model.getAttribute("gapSellerStar"));
        System.out.println(model.getAttribute("gapBabyStar"));

        model.addAttribute("stayReply", stayReply);
        model.addAttribute("thisWeekGood", thisWeekGood);
        model.addAttribute("thisMonthOneGood", thisMonthOneGood);
        model.addAttribute("thisMonthSixGood", thisMonthSixGood);
        model.addAttribute("thisWeekMedium", thisWeekMedium);
        model.addAttribute("thisMonthOneMedium", thisMonthOneMedium);
        model.addAttribute("thisMonthSixMedium", thisMonthSixMedium);
        model.addAttribute("thisWeekBad", thisWeekBad);
        model.addAttribute("thisMonthOneBad", thisMonthOneBad);
        model.addAttribute("thisMonthSixBad", thisMonthSixBad);
        model.addAttribute("thisWeekCount", thisWeekCount);
        model.addAttribute("thisMonthOneCount", thisMonthOneCount);
        model.addAttribute("thisMonthSixCount", thisMonthSixCount);
        model.addAttribute("allEvaluation", allEvaluation);


        return "include/seller/evaluation_center";
    }

    /**
     * 前往买家管理评价页面
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/evaluationManagement")
    public String goEvaluationManagement(HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        int slId = sellerService.findSellerIdByUserId(user.getUserId()).getId();
        SuperEvaluationFind superEvaluationFind = new SuperEvaluationFind();
        superEvaluationFind.setSlid(slId);
        superEvaluationFind.setIsTerm(0);
        superEvaluationFind.setPaginationCurrent(1);
        superEvaluationFind.setPaginationPageSize(5);
        List<ProductComment> comments = evaluationService.findUserAllEvaluationBySlid(superEvaluationFind);
        model.addAttribute("comments", comments);
        return "include/seller/evaluation_management";
    }

    /**
     * 跳转至出售中的宝贝
     * @return
     */
    @RequestMapping("/render")
    public String goOnSaleBaby(){
        return "/include/seller/render";
    }

    /**
     * 跳转至已删除的历史宝贝，商品回收站
     * @return
     */
    @RequestMapping("/productRecycle")
    public String goProductRecycle(){
        return "include/seller/product_recycle";
    }


    @RequestMapping("/dispute/detail")
    public String goRefundDetail(@RequestParam("bizOrderId") String marketOdd, @RequestParam("detailId") int msroId,
                                 @RequestParam("bizReturnId") String returnOdd, Model model){
        // 根据参数上的单号和Id拿到所有的实体
        // 获得当前售后的总订单，详情订单
        MarketOrder marketOrder = orderService.findAllOrder(marketOdd, 2, 0).get(0);
        // 根据订单详情id获得指定的订单详情实体
        MarketSrOrder marketSrOrder = null;
        for (MarketSrOrder srOrder : marketOrder.getMarketSrOrderList()) {
            if(srOrder.getId() == msroId){
                marketSrOrder = srOrder;
                break;
            }
        }

        PrimaryReturn primaryReturn = returnService.findPrimaryReturnAllDetailByReturnOdd(returnOdd);
        // 获得这次订单的买家给卖家看
        User buyerUser =sellerService.findUserByUid(marketOrder.getUser().getUserId());
        // 存
        model.addAttribute("marketOrder", marketOrder);
        model.addAttribute("marketSrOrder", marketSrOrder);
        model.addAttribute("primaryReturn", primaryReturn);
        model.addAttribute("buyerUser", buyerUser);
        return "include/seller/return_detail";
    }


    /**
     * 跳转至拒绝售后
     * @return
     */
    @RequestMapping("dispute/sellerRefuseDispute")
    public String goSellerRefuseDispute(@RequestParam("bizOrderId") String marketOdd, @RequestParam("detailId") int msroId,
                                        @RequestParam("bizReturnId") String returnOdd, Model model){
        // 根据参数上的单号和Id拿到所有的实体
        // 获得当前售后的总订单，详情订单
        MarketOrder marketOrder = orderService.findAllOrder(marketOdd, 2, 0).get(0);
        // 根据订单详情id获得指定的订单详情实体
        MarketSrOrder marketSrOrder = null;
        for (MarketSrOrder srOrder : marketOrder.getMarketSrOrderList()) {
            if(srOrder.getId() == msroId){
                marketSrOrder = srOrder;
                break;
            }
        }

        PrimaryReturn primaryReturn = returnService.findPrimaryReturnAllDetailByReturnOdd(returnOdd);
        // 获得这次订单的卖家给用户看
        User sellerUser = sellerService.findUserBySlid(marketOrder.getSlid());
        // 存
        model.addAttribute("marketOrder", marketOrder);
        model.addAttribute("marketSrOrder", marketSrOrder);
        model.addAttribute("primaryReturn", primaryReturn);
        model.addAttribute("sellerUser", sellerUser);
        return "include/seller/seller_refuse_dispute";
    }

    /**
     * 进入店铺管理
     * @return
     */
    @RequestMapping("/shopManagement")
    public String goShopManagement(){
        return "/include/seller/shop_management";
    }


    /**
     * 前往申请卖家
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/applySeller")
    public String goApplySeller(HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        ApplySeller applySeller = sellerService.findUserApplySellerStatus(user.getUserId());
        int status = 0;
        if(null == applySeller){
            status = -1;
        } else{
            status = applySeller.getApplyStatus();
        }
        model.addAttribute("status", status);
        return "include/seller/apply_seller";
    }


    /**
     * 获取商品类别父节点ID
     * @param cid
     * @return
     */
    public int getParentCategoryId(int cid){
        int parentId = 0;
        try {
            Category category = categoryService.byIdFindCategory(cid);
            String[] paths = category.getPath().split(",");
            parentId = Integer.parseInt(paths[paths.length-1]);
        } catch (NullPointerException e){
            return 99999;
        }
        return parentId;
    }

}
